//
//  JShopCarSelBtnView.m
//  HeadIndustry
//
//  Created by jun on 2017/9/1.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JShopCarSelBtnView.h"

@implementation JShopCarSelBtnView

- (instancetype)initWithFrame:(CGRect)frame  dataArr:(NSArray *)arr
{
    if (self = [super initWithFrame:frame]) {
        
        _dataArr = arr;
        self.backgroundColor = [UIColor whiteColor];
        self.opaque = NO;
        _imgBtnArr = [NSMutableArray array];
        [self setUpView];
        [self creatBtn:arr];
    }
    return  self;
}

- (void)setUpView {
    YYLabel *title = [YYLabel new];
    title.left = 10;
    title.top = 10;
    title.size = CGSizeMake(80, 30);
    title.font = kFONT_TITLE(16);
    title.textColor = [UIColor blackColor];
    [self addSubview:title];
    _textSizeLa = title;
}

- (void)creatBtn:(NSArray *)btnArr
{
    _currentBtn = -1;
    CGFloat width = (kWindowW - 25)/4.0;
    CGFloat height = 30;
    for (int i = 0; i < btnArr.count; i++) {
        YYLabel *label = [YYLabel new];
        label.frame = CGRectMake(5 + (width + 5) * (i % 4), 40  + 5+ (height + 10) * (i / 4), width, height);
        label.text = btnArr[i][@"name"];
        label.tag =  i;
        label.font = kFONT_TITLE(12);
        label.textColor = kRGBColor(101, 101, 101);
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.borderColor = kRGBColor(150, 150, 150).CGColor;
        label.layer.borderWidth = 0.5;
        label.layer.cornerRadius = 3;
        label.layer.masksToBounds = YES;
        [self addSubview:label];
        
        CALayer *imgLayer = [CALayer layer];
        imgLayer.left = label.width - 20;
        imgLayer.top = 10;
        imgLayer.size = CGSizeMake(20, 20);
        imgLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"yexicon"].CGImage);
        [label.layer addSublayer:imgLayer];
        imgLayer.hidden = YES;
        [_imgBtnArr addObject:imgLayer];
        
        label.textTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            YYLabel *label = (YYLabel *)containerView;
            [self BtnSelClick:label];
        };
    }
}

- (void)BtnSelClick:(YYLabel *)btn
{
    if (_currentBtn == btn.tag) {
        return;
    }
    
    for (CALayer *imgLayer in _imgBtnArr) {
        imgLayer.hidden = YES;
    }
    CALayer *imgLayer = _imgBtnArr[btn.tag];
    imgLayer.hidden = NO;
    
    if (_selBtnBlock) {
        _selBtnBlock(btn.tag);
    }
    
    _currentBtn = btn.tag;
}

- (void)setAttributeModel:(JProductAttributeModel *)attributeModel
{
    _attributeModel = attributeModel;
    _textSizeLa.text = attributeModel.product_attribute_name;
}

- (CGFloat) getViewHeight
{
    CGFloat height = 40 + 5+ 40 * (_dataArr.count / 4 + 1);
    return height;
}

@end
